<?php

namespace App\Http\Controllers\Admin;

use App\Models\ArticleCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleCateController extends Controller
{
    /**
     *  分类列表
     */
    public function index($pid=0)
    {

        return view('admin.article_cate.index',['pid' => $pid]);
    }

    public function indexPost(Request $request)
    {
        $input = $request->all();
        $condition = [
            'condition' => [
                [
                    'where',
                    ['where','pid = ?']
                ]
            ]
        ];
        $serach = ['0'];
        if($request->has('serach_name')){
            //dd($request->input('serach_name'));
            $condition = [
                'condition' => [
                    [
                        'where',
                        ['where','name like %?%']
                    ]
                ]
            ];
            $serach[0] = $request->input('serach_name');
        }
        if($request->has('pid')){
            $condition = [
                'condition' => [
                    [
                        'where',
                        ['where','pid = ?']
                    ]
                ]
            ];
            $serach = [$request->input('pid')];
        }
        $dd = (new ArticleCategory())->dataTable10(['*'], $input ,$condition, $serach);
        return response()->json($dd);
    }

    /**
     *  添加分类
     */
    public function addCate()
    {
        $all_cate = (new ArticleCategory())->arrayAllCate();

        return view('admin.article_cate.addCate',['allcate'=>$all_cate]);
    }

    public function addCatePost(Request $request)
    {
        $input = [
            'name' => $request->input('name'),
            'pid' => $request->input('pid'),
        ];
        if($request->has('id')){
            $res = ArticleCategory::find($request->input('id'))->update($input);
        }else{
            $res = ArticleCategory::create($input);
        }

        if($res){
            return response()->json(['code'=>1, 'msg'=> '成功']);
        }else{
            return response()->json(['code'=>0, 'msg'=> '失败']);
        }
    }

    /**
     *  编辑分类
     */
    public function editCate($id = 0)
    {
        $all_cate = (new ArticleCategory())->arrayAllCate();
        $cate_info = ArticleCategory::find($id);

        return view('admin.article_cate.addCate',['id'=>$id,'allcate'=>$all_cate,'cate_info'=>$cate_info]);
    }

    /**
     *  删除分类
     */
    public function delCate(Request $request)
    {
        $id = $request->input('id');
        //检测,是否有下级,是否还有文章..
        $res = ArticleCategory::find($id)->delete();
        if($res){
            return response()->json(['code'=>1, 'msg'=>'成功']);
        }else{
            return response()->json(['code'=>0, 'msg'=>'失败']);
        }
    }

}
